<template>
  <div class="bigbox">
    <!-- 左侧盒子 -->
    <div class="leftbox">
      <div class="title">
        <el-autocomplete
          class="inline-input"
          v-model="filterText"
          size="small"
          :fetch-suggestions="querySearch"
          placeholder="输入关键字进行过滤"
          :trigger-on-focus="true"
          value-key="name"
          :debounce='300'
          style="width: 100%"
          @select="handleSelect"
        ></el-autocomplete>
        <!-- <span><button @click="addtianjia">添加</button></span> -->
      </div>
      <!-- 树组件 -->
      <div class="treebox">
        <el-tree
          check-strictly
          :props="props"
          :load="loadNode"
          :highlight-current="true"
          lazy
          show-checkbox
          @check="handClick"
          node-key="id"
          :default-expanded-keys="array"
          @node-click="handleNodeClick"
          ref="tree"
          >
          <template slot-scope="{ node, data }">
            <span :style="{
              color:data.collect ?'':data.className=='FactoryStation'?'#999':'',
              'font-size':data.collect ?'':data.className=='FactoryStation'?'14px':''}">
             <img
              :src="'data:image/png;base64,' + data.iconBase64"
              style="
                width: 16px;
                height: 16px;
                margin-right: 5px;
                vertical-align: bottom;"/> {{ node.label }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <!-- 盒子主体 -->
    <div class="bodybox">
      <div class="title">
        <el-form ref="form" label-position="left" label-width="40px">
            <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="日期">
                    <el-date-picker
                      v-model="value1"
                      size="small"
                      type="datetimerange"
                      range-separator="至"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-form-item label="">
                    <el-button size="small" type="primary" @click="chaxun">查 询</el-button>
                    <el-button size="small" type="primary" @click="daochu">导 出</el-button>
                  </el-form-item>
                </el-col>
            </el-row>
        </el-form>
      </div>
     <!-- checkbox测点多选框 -->
      <div class="xunhuan">
        <el-checkbox-group v-model="checkedCities">
          <el-checkbox v-for="(item,index) in leilist" :label="item.value" :key="index">{{item.text}}</el-checkbox>
        </el-checkbox-group>
      </div>
      <!-- tag标签 -->
      <!-- <div class="tages">
        <el-tag v-for="tag in tags" :key="tag.name" closable type="" @close="handleClose(tag)" :closable="true"> {{tag.name}}</el-tag>
      </div> -->
      <!-- echart图表区域 -->
      <div class="echarts" ref="tanbutan"></div>
      <!-- table表格区域 -->
      <div class="table">
        <template>
          <el-table
            :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
            style="width: 100%">
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column prop="date" label="日期" width="200" align="center" v-if="devices.length"></el-table-column>
            <el-table-column v-for="(device,index) in devices" :key="index"  :label="device.label" align="center">
              <el-table-column v-for="(item,indexs) in device.childrenlist" :key="indexs" :prop="item.prop" :label="item.label" align="center">
              </el-table-column>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div style="text-align: right;">
        <el-pagination background  @current-change="handleCurrentChange" 
        :current-page="currentPage"  :page-size="pageSize"
        layout="prev, pager, next" :total="tableData.length">
				</el-pagination>
      </div>
    </div>

  </div>
</template>

<script>
import {getzidianxialaapi} from '@/api/guidelines'
import { getgenjiedianapi, getzijidianapi } from '@/api/monitor'
import { getKeywordListApi } from '@/api/Ledger'
import * as echarts from 'echarts';
import { getduometerlistapi } from '@/api/monitor'
import { exportexcel } from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',

  data() {
    return {
      value1:[],
      filterText: '',
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      tableData:[],
      treevalue:{},
      array: [],
      checkedCities: [],
      leilist: [],
      tags: [],
      devices: [],
      currentPage: 1, // 当前页码
			  total: 0, // 总条数
			  pageSize: 10 // 每页的数据条数
    };
  },

  async mounted() {
    const res = await getzidianxialaapi({ dictType: 'PDYW_CDBS' })
    this.leilist = res.data.list
    this.checkedCities.push(res.data.list[0].value)
    this.checkedCities.push(res.data.list[1].value)
    this.gettime()
  },

  methods: {
    // 查询
    async chaxun() {
      // if(==0) return 
      if (this.checkedCities.length == 0) return this.$message.warning('请先选择测点标识') 
      if (this.tags.length) {
        const deviceIds=this.tags.map(ele=>ele.id)
      const {data:{list}}= await getduometerlistapi({
        deviceIds: deviceIds.join(','),
        itemTags: this.checkedCities.join(','),
        startTime:this.value1[0],endTime:this.value1[1]
      })
      this.total=list.length
      this.getechart(list)
      const array= this.leilist.map(ele => {
        for (let i = 0; i < this.checkedCities.length; i++) {
          if (ele.value == this.checkedCities[i]) {
            return ele
          }
        }
      })
      this.generateTableData(this.tags,array,list)
      }else{
        this.$message.warning('请先添加设备') 
        this.tableData = [];
        this.devices=[]
        this.getechart([])
      }

    },
    generateTableData(tags, array, list) {
      // 处理表头数据
      const arr3= array.filter(ele => {
        if (ele) {
          return ele
          }
        })
      const tabletitlelist = []
      let num=0
        for (let i = 0; i < this.tags.length; i++) {
          if (!i) {
            num += this.checkedCities.length - 1
          } else {
            num += this.checkedCities.length
          }
          tabletitlelist.push({
            label: list[num].deviceName,
            childrenlist:[]
          })
        }
        arr3.map(ele => {
          for (let i = 0; i < tabletitlelist.length; i++){
            tabletitlelist[i].childrenlist.push({
              label: ele.text,
              prop:ele.value
            })
          }
        })
        let propIndex = 0;
        tabletitlelist.forEach((item, index) => {
          item.childrenlist.forEach((child, childIndex) => {
            child.prop = child.prop + propIndex;
            propIndex++;
          });
        });
        // tabletitlelist.unshift({label:'日期',prop:'date',childrenlist:[]})
      this.devices = tabletitlelist
      // 处理表格数据
      const tableData = [];

    // 遍历时间点数组
    list[0].timePoints.forEach((timePoint, index) => {
        const obj = { date: timePoint };
        list.forEach((item,xia) => {
            const dataIndex = index < item.itemPoints.length ? index : item.itemPoints.length - 1;
            const key = `${item.itemTag}${xia}`;
            obj[key] = item.itemPoints[dataIndex] === null ? '' : item.itemPoints[dataIndex];
        });
        tableData.push(obj);
    });
      this.tableData = tableData
    },
    // 导出
    daochu() {
      if(this.tags.length==0) return this.$message.warning('请先添加设备') 
      if(this.checkedCities.length==0) return this.$message.warning('请先选择测点标识') 
      const deviceIds=this.tags.map(ele=>ele.id)
      exportexcel('pio-microservice-biz/pio/iot-item/his/bitch/excel', {
        deviceIds: deviceIds.join(','),
        itemTags: this.checkedCities.join(','),
        startTime:this.value1[0],endTime:this.value1[1]
      },'运行分析')
    },
    // 分页页数发生便是处理
    handleSizeChange(val) {
			this.currentPage = 1;
			this.pageSize = val;
    },
    // 分页页码发生改变时
		handleCurrentChange(val) {
			this.currentPage = val;
		},
    // 添加tags
    addtianjia() {
      this.tags.push(this.treevalue)
    },
    // 移除tags
    handleClose(val) {
      this.tags=this.tags.filter(ele=>ele.id!==val.id)
    },
   // 树节点搜索
   async querySearch (queryString, cb) {
      const res = await getKeywordListApi({ name: queryString })
      const restaurants = res.data.list
      cb(restaurants)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect (item) {
      const newarr = item.pathId.split(',')
      for (let i = 0; i < newarr.length; i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      function getgaoliang (that) {
        const node = that.$refs.tree.getNode(item)
        if (node) {
          that.$refs.tree.setCurrentKey(item.id)
        } else {
          setTimeout(() => {
            getgaoliang(that)
          }, 500)
        }
      }
      getgaoliang(this)
      this.handleNodeClick(item)
    },
    // 设备树点击事件
    async handleNodeClick(val, node) {
      this.treevalue=val
    },
    handClick() {
      this.tags = this.$refs.tree.getCheckedNodes(false, true)
      this.chaxun()
    },
   // 设备树懒加载
   async loadNode (node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'DeviceManageTree' })
      // const res = await getzijidianapi()
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) { // 初始的级数（最顶层）
        return resolve(ress.data.list) // 最顶层数据渲染为region
      }
      if (node.level === 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 3) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 4) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 5) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 6) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 获取当前时间戳
    gettime() {
      this.valueri = []
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() //日
        let hours = date.getHours();
        let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      this.value1.push(year + '-' + month + '-' + day + ' ' + '00' + ':' + '00' + ':' + '00')
      this.value1.push(year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds)
      
    },
    // 获取echart图表
    getechart(list) {
      const timePoints=list[0]?.timePoints
      const series= list.map(ele => {
        return {
              data: ele.itemPoints,
              type: 'line',
              name:ele.deviceName+ele.itemTagName,
              symbol: "none",
              markPoint: {
              data: [
                { type: 'max', label:{color:'#fff'} },
                { type: 'min', label:{color:'#fff'} }
              ]
            },
        }
      })
      var chartDom = this.$refs.tanbutan
      var myChart = echarts.init(chartDom);
      var option;
     option = {
      xAxis: {
            type: 'category',
            data: timePoints
        },
        grid: {
          left: '5%',
          right: '5%',
       },
       legend: {},
          yAxis: {
                  axisLine:{show: true},
                  splitLine: {
                    //网格线
                    lineStyle: {
                      type: 'dashed' //设置网格线类型 dotted：虚线   solid:实线
                    },
                    show: true //隐藏或显示
                  },
                  type: 'value'
                },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
                  feature: {
                    saveAsImage: {}
                  }
                },
          dataZoom: [
                  {
                    type: 'slider',
                    xAxisIndex: 0,
                    filterMode: 'none'
                  },
                  {
                    type: 'slider',
                    yAxisIndex: 0,
                    filterMode: 'none'
                  },
                  {
                    type: 'inside',
                    xAxisIndex: 0,
                    filterMode: 'none'
                  },
                  {
                    type: 'inside',
                    yAxisIndex: 0,
                    filterMode: 'none'
                  }
                ],
       series: series
      };
      
      myChart.clear();
      option && myChart.setOption(option);
    }
  },
};
</script>

<style scoped>
.bigbox{
  padding: 10px;
  height: 100%;
  display: flex;
  .leftbox{
    width: 300px;
    background-color: #fff;
    height: auto;
    padding:20px 15px;
    .title{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      button{
      width: 60px;
      height: 30px;
      border: none;
      border-radius: 3px;
      color: #fff;
      background-color: #1a90fe;
      }
    }

    .treebox{
      height: 92%;
      overflow: hidden;
      overflow-y: auto;
    }
  }
  .bodybox{
    overflow-y: auto; /* 当内容过多时显示滚动条 */

    margin-left: 10px;
    padding: 20px;
    height: 100%;
    background-color: #fff;
    width: calc(100% - 310px);
    .xunhuan{
      /* margin-top: 10px; */
      padding: 10px 0;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
    }
    .table{
      margin: 10px 0;
    }
    .tages{
      margin-top: 10px;
    }
    .echarts{
      height: 300px;
    }
  }
}
::v-deep .el-tree-node__content {
  font-size: 14px; /* 修改为你想要的字体大小 */
}
.xunhuan{
  ::v-deep .el-checkbox-group{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
::v-deep .el-checkbox{
 width: 12%;
 margin-bottom: 10px;
}
::v-deep .el-tag--light{
  margin:0 10px 10px 0;
  padding: 0 10px;
}
}

</style>